package cn.hzking.gjmall.delegates.main;


import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.fingdo.statelayout.StateLayout;
import com.google.gson.Gson;
import com.mikhaellopez.circularimageview.CircularImageView;

import java.util.List;

import butterknife.Bind;
import butterknife.OnClick;
import cn.hzking.gjmall.R;
import cn.hzking.gjmall.activitys.second.GoodActiivtyActivity;
import cn.hzking.gjmall.activitys.second.SearchActivity;
import cn.hzking.gjmall.adpters.home.HeadLineAdpter;
import cn.hzking.gjmall.adpters.home.HomeDataAdapter;
import cn.hzking.gjmall.adpters.home.SubareaAdpter;
import cn.hzking.gjmall.base.BaseDelegate;
import cn.hzking.gjmall.bean.HomeDataBean;
import cn.hzking.gjmall.greendao.GreenDaoManager;
import cn.hzking.gjmall.greendao.HomeCacheBeanDao;
import cn.hzking.gjmall.greendao.beans.HomeCacheBean;
import cn.hzking.gjmall.net.RetrofitOssFactory;
import cn.hzking.gjmall.net.base.GjObserver;
import cn.hzking.gjmall.utils.AndroidStudioUtils;
import cn.hzking.gjmall.utils.SPUtils;
import cn.hzking.gjmall.utils.SwipeRefreshLayoutUtils;
import cn.hzking.gjmall.utils.helpers.ConvenientBannerHelper;
import cn.hzking.gjmall.view.convenientbanner.ConvenientBanner;

/**
 * A simple {@link Fragment} subclass.
 */
public class HomeDelegate extends BaseDelegate {


    @Bind(R.id.home_bar_headimage)
    CircularImageView homeBarHeadimage;
    @Bind(R.id.home_bar_name)
    TextView homeBarName;
    @Bind(R.id.home_bar_detail)
    TextView homeBarDetail;
    @Bind(R.id.rl_bar_search)
    RelativeLayout rlBarSearch;
    @Bind(R.id.recyclerview)
    RecyclerView recyclerview;
    @Bind(R.id.refrsh)
    SwipeRefreshLayout refrsh;
    @Bind(R.id.statlayout)
    StateLayout statlayout;
    private HomeDataAdapter homeDataAdapter;
    private HomeCacheBeanDao homeCacheBeanDao;
    private List<HomeCacheBean> list;
    private ConvenientBanner convenientBanner;

    public HomeDelegate() {
        // Required empty public constructor
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
       // Log.e("hh","fragment------oncreat");
    }

    @Override
    public Object setLayout() {
        return R.layout.fragment_home_delegate;
    }

    @Override
    public void onBindView(@Nullable Bundle savedInstanceState, View rootView) {
    //    Log.e("hh","fragment------oncreatview");
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(_mActivity);
        recyclerview.setLayoutManager(linearLayoutManager);
        homeDataAdapter = new HomeDataAdapter(null);
        recyclerview.setAdapter(homeDataAdapter);
        recyclerview.scrollToPosition(0);
        SwipeRefreshLayoutUtils.initRefreshLayout(refrsh);
        //下拉刷新
        refrsh.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                initData(_mActivity,statlayout,refrsh,false,true,false,false);
            }
        });
        //加载更多
        homeDataAdapter.setOnLoadMoreListener(new BaseQuickAdapter.RequestLoadMoreListener() {
            @Override
            public void onLoadMoreRequested() {

            }
        });

    }

    @Override
    public void onLazyInitView(@Nullable Bundle savedInstanceState) {
        super.onLazyInitView(savedInstanceState);
        //设置头像
        String headPic = SPUtils.getHeadPic(_mActivity);
        Glide.with(_mActivity).load(headPic).into(homeBarHeadimage);
        //店铺名称
        homeBarName.setText(String.valueOf(SPUtils.getShopName(_mActivity)));
        //店铺详情
        homeBarDetail.setText(String.valueOf(SPUtils.getShopDes(_mActivity)));
        homeCacheBeanDao = GreenDaoManager.getInstance().getSession().getHomeCacheBeanDao();
        HomeCacheBean homeCacheBean = homeCacheBeanDao.load(1L);
        if( homeCacheBean != null){//数据库有缓存
            if(AndroidStudioUtils.getVersionCode(_mActivity) <= homeCacheBean.getVersionCode()) {//当前版本和数据库储存的版本信息相同
                String json = homeCacheBean.getJson();
                Gson gson = new Gson();
                HomeDataBean homeDataBean = gson.fromJson(json, HomeDataBean.class);
                HomeDataBean.DataBean data = homeDataBean.getData();
                if (data != null) {
                    homeDataAdapter.setNewData(data.getTemplate());
                    initFirstHeader(data);
                    initSecondHeadr(data);
                    recyclerview.scrollToPosition(0);
                    homeDataAdapter.loadMoreEnd(false);
                    initData(_mActivity,statlayout,refrsh,false,false,false,false);
                }
            }
        }else {//第一次登录,或者说app版本更新了
             initData(_mActivity,statlayout,refrsh,true,false,true,false);
        }
    }

    private void initData(Activity cxt, StateLayout stateLayout, SwipeRefreshLayout swipeRefreshLayout , boolean isFistInit, boolean isRefresh,boolean isShowDilog ,boolean cancel) {
        RetrofitOssFactory.getInstant().API().getHomeData()
                .compose(this.<HomeDataBean>setThread())
                .subscribe(new GjObserver<HomeDataBean>(cxt,stateLayout,swipeRefreshLayout,isFistInit,isRefresh,isShowDilog,cancel) {
                    @Override
                    protected void onBusinessSuccess(HomeDataBean homeDataBean) throws Exception {
                        Gson gson = new Gson();
                        String cacheData = gson.toJson(homeDataBean);//需要缓存到数据库的数据
                        int versionCode = AndroidStudioUtils.getVersionCode(_mActivity);
                        if(homeCacheBeanDao.load(1L) ==null) {//第一次存储
                            HomeCacheBean homeCacheBean = new HomeCacheBean();
                            homeCacheBean.setContentId(1);
                            homeCacheBean.setVersionCode(versionCode);
                            homeCacheBean.setJson(cacheData);
                            homeCacheBeanDao.insert(homeCacheBean);
                        }else {//不是第一次存储,更新数据
                            HomeCacheBean homeCacheBean1 = homeCacheBeanDao.load(1L);
                            homeCacheBean1.setJson(cacheData);
                            homeCacheBean1.setVersionCode(versionCode);
                            homeCacheBean1.setContentId(1);
                            homeCacheBeanDao.update(homeCacheBean1);

                        }
                        HomeDataBean.DataBean data = homeDataBean.getData();
                        if( data != null){
                            homeDataAdapter.removeAllHeaderView();
                            homeDataAdapter.setNewData(data.getTemplate());
                            initFirstHeader(data);
                            initSecondHeadr(data);
                            homeDataAdapter.loadMoreEnd(false);
                        }

                    }

                    @Override
                    protected void onChildFailure(Throwable e, boolean isNetWorkError) throws Exception {

                    }
                });

    }

    /**
     * 加载第二个布局
     * @param data
     */
    private void initSecondHeadr(HomeDataBean.DataBean data) {
        if(data.getSubarea() != null && data.getSubarea().size() >0){//添加中间品牌馆布局
            View view = LayoutInflater.from(_mActivity).inflate(R.layout.item_subareas,null);
            RecyclerView sRecyclerview = view.findViewById(R.id.subarue_list);
            final List<HomeDataBean.DataBean.SubareaBean> subareas = data.getSubarea();
            GridLayoutManager gridLayoutManager = new GridLayoutManager(_mActivity, 3);
            sRecyclerview.setLayoutManager(gridLayoutManager);
            SubareaAdpter subareaAdpter = new SubareaAdpter(R.layout.item_home_subarea, subareas);
            sRecyclerview.setAdapter(subareaAdpter);
            gridLayoutManager.setSpanSizeLookup(new GridLayoutManager.SpanSizeLookup() {
                @Override
                public int getSpanSize(int position) {
                    if(subareas.size() == 5){
                        if(position == 0){
                            return 2;
                        }else {
                            return 1;
                        }
                    }else if(subareas.size() == 6){
                        return 1;
                    }

                    return 0;
                }
            });
            homeDataAdapter.addHeaderView(view,1);
        }
    }

    /**
     * 添加第一个header
     * @param data
     */
    private void initFirstHeader(HomeDataBean.DataBean data) {
        if(data.getCarouse() != null && data.getHeadline() != null){
            //加载轮播图
            View view = LayoutInflater.from(_mActivity).inflate(R.layout.item_homepage_header_one,null);
           convenientBanner = view.findViewById(R.id.home_banner);
            new ConvenientBannerHelper(_mActivity,convenientBanner,data.getCarouse()).initConvenientBanner();
            convenientBanner.startTurning(3000);
            //加载关键字
            RecyclerView headerLineRecyclerview = view.findViewById(R.id.home_sort_list);
            LinearLayoutManager linearLayoutManager = new LinearLayoutManager(_mActivity);
            linearLayoutManager.setOrientation(LinearLayoutManager.HORIZONTAL);
            headerLineRecyclerview.setLayoutManager(linearLayoutManager);
            List<HomeDataBean.DataBean.HeadlineBean> headlines = data.getHeadline();
            HeadLineAdpter headLineAdpter = new HeadLineAdpter(R.layout.item_text_item, headlines);
            headerLineRecyclerview.setAdapter(headLineAdpter);
            //添加头布局
            homeDataAdapter.addHeaderView(view,0);

        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
      //  Log.e("hh","fragment------onDestroy");
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
      //  Log.e("hh","fragment------onDestroyView");
    }

    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
     if(hidden){
        if(convenientBanner != null){
            convenientBanner.stopTurning();
        }
     }else {
         if(convenientBanner != null){
             convenientBanner.startTurning(3000);
         }
     }
    }

    //点击搜索跳转
    @OnClick(R.id.rl_bar_search)
    public void submit(View view) {
        Intent intent = new Intent(_mActivity, SearchActivity.class);
        _mActivity.startActivity(intent);
    }
    @OnClick(R.id.home_bar_headimage)
    public void headImage(View view){
       /* Intent intent = new Intent(_mActivity, NYuanGoodListActivity.class);
        startActivity(intent);*/
       Intent intent = new Intent(_mActivity, GoodActiivtyActivity.class);
       startActivity(intent);
    }
}
